package com.shuoyue.ycgk.base;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.core.widget.NestedScrollView;
import androidx.lifecycle.Lifecycle;

import com.gyf.immersionbar.ImmersionBar;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.shuoyue.appdepends.base.BaseActivity;

import com.shuoyue.ycgk.R;
import com.shuoyue.ycgk.appcatch.MemeryCatch;
import com.shuoyue.ycgk.appcatch.SPUtils;
import com.shuoyue.ycgk.base.baseadapter.AppBaseQuickAdapter;
import com.shuoyue.ycgk.net.exception.NetErrorException;
import com.shuoyue.ycgk.ui.account.login.LoginActivity;
import com.shuoyue.ycgk.utils.XToast;
import com.shuoyue.ycgk.views.dialog.SpotsDialog;
import com.uber.autodispose.AutoDispose;
import com.uber.autodispose.AutoDisposeConverter;
import com.uber.autodispose.android.lifecycle.AndroidLifecycleScopeProvider;

import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;

import static com.mobile.auth.gatewayauth.utils.ReflectionUtils.getActivity;

/**
 * @author azheng
 * @date 2018/4/24.
 * GitHub：https://github.com/RookieExaminer
 * Email：wei.azheng@foxmail.com
 * Description：
 */
public abstract class BaseMvpActivity<T extends BasePresenter> extends BaseActivity implements BaseView {

    protected T mPresenter;
    SpotsDialog spotsDialog;
    protected CompositeDisposable mCompositeDisposable;
    protected boolean isUseSelfImmersionBar = false;//是否自行定制状态栏，在super.oncreate前指定
    protected boolean isHiddSoftInput = true;//


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        mCompositeDisposable = new CompositeDisposable();
        super.onCreate(savedInstanceState);
        if (isHiddSoftInput)
            getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        if (!isUseSelfImmersionBar) {
            ImmersionBar.with(this)
//                .statusBarAlpha(0.8f)  //状态栏透明度，不写默认0.0f
                    .statusBarColor(R.color.statueBar)     //状态栏颜色，不写默认透明色
                    .autoStatusBarDarkModeEnable(true, 0.2f) //自动状态栏字体变色，必须指定状态栏颜色才可以自动变色哦
                    .statusBarDarkFont(false, 0.2f)
                    .init();
        }
    }

    @Override
    protected void onPause() {
        Log.e("act", "onPause");
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        if (mCompositeDisposable != null) {
            mCompositeDisposable.clear(); // clear时网络请求会随即cancel
            mCompositeDisposable = null;
        }
        if (mPresenter != null) {
            mPresenter.detachView();
        }
        Log.e("act", "destroy");
        super.onDestroy();
    }

    /**
     * 绑定生命周期 防止MVP内存泄漏
     *
     * @param <T>
     * @return
     */
    @Override
    public <T> AutoDisposeConverter<T> bindAutoDispose() {
        return AutoDispose.autoDisposable(AndroidLifecycleScopeProvider
                .from(this, Lifecycle.Event.ON_DESTROY));
    }

    @Override
    public void bindDispos(Disposable disposable) {
        if (mCompositeDisposable == null || mCompositeDisposable.isDisposed()) {
            mCompositeDisposable = new CompositeDisposable();
        }
        mCompositeDisposable.add(disposable);
    }

    @Override
    public void showLoading(String title) {
        if (spotsDialog == null) {
            spotsDialog = new SpotsDialog(mContext, title);
        }
        if (!TextUtils.isEmpty(title)) {
            spotsDialog.setText(title);
        } else {
            spotsDialog.setText("");
        }
        if (!spotsDialog.isShowing()) {
            spotsDialog.show();
        }
    }

    @Override
    public void showLoading() {
        showLoading("请稍候~");
    }

    @Override
    public void hideLoading() {
        if (spotsDialog != null && spotsDialog.isShowing()) {
            spotsDialog.dismiss();
        }
        if (smartRefreshLayout != null) {
            smartRefreshLayout.finishRefresh();
            smartRefreshLayout.finishLoadMore();
        }
    }

    /**
     * 此方法只是关闭软键盘
     */
    protected void hintKbTwo() {
        InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm.isActive() && getActivity().getCurrentFocus() != null) {
            if (getActivity().getCurrentFocus().getWindowToken() != null) {
                imm.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }

    SmartRefreshLayout smartRefreshLayout;

    public void registFinishLoad(SmartRefreshLayout smartRefreshLayout) {
        this.smartRefreshLayout = smartRefreshLayout;
//        smartRefreshLayout.setEnableLoadMore(false);
    }

    public void registEmptyView(AppBaseQuickAdapter mAdapter) {
        registEmptyView(mAdapter, null);
    }

    public void registEmptyView(AppBaseQuickAdapter mAdapter, int emptyViewRes) {
        View layEmpty = LayoutInflater.from(mContext).inflate(emptyViewRes, null, false);
        mAdapter.setEmptyView(layEmpty);
    }

    public void registSimpleTextEmptyView(AppBaseQuickAdapter mAdapter, String text) {
        View layEmpty = LayoutInflater.from(mContext).inflate(R.layout.lay_empty_simple_text, null, false);
        TextView tvTips = layEmpty.findViewById(R.id.text);
        tvTips.setText(text);
        mAdapter.setEmptyView(layEmpty);
    }

    public void registEmptyView(AppBaseQuickAdapter mAdapter, String tips) {
        View layEmpty = LayoutInflater.from(mContext).inflate(R.layout.layout_empty, null, false);
        TextView tvTips = layEmpty.findViewById(R.id.title);
        if (tips != null)
            tvTips.setText(tips);

        mAdapter.setEmptyView(layEmpty);
    }

    public void registEmptyViewWrapHeight(AppBaseQuickAdapter mAdapter, String tips) {
        View layEmpty = LayoutInflater.from(mContext).inflate(R.layout.layout_empty_wrap, null, false);
        TextView tvTips = layEmpty.findViewById(R.id.title);
        if (tips != null)
            tvTips.setText(tips);

        mAdapter.setEmptyView(layEmpty);
    }

    @Override
    public void clearUserInfo() {
//        SPUtils.clearUserInfo(mContext);
//        SPUtils.clearToken(mContext);
//        SPUtils.clearLoginUserName(mContext);
//        MemeryCatch.token = "";
    }

    boolean isJumpToLogin = false;//防止多个请求重复

    public void needLogin() {
        if (!isJumpToLogin) {
            SPUtils.clearUserInfo(mContext);
            MemeryCatch.token = "";
//            startActivityForResult(new Intent(this, AccountLoginActivity.class)
//                            .putExtra("requestCode", AccountLoginActivity.REQUEST_CODE),
//                    AccountLoginActivity.REQUEST_CODE);
//            AccountLoginActivity.startForResult(this);
//            startActivityForResult(new Intent(this, LoginActivity.class)
//                            .putExtra("srequestCode", LoginActivity.REQUEST_CODE),
//                    LoginActivity.REQUEST_CODE);
            LoginActivity.start(this);
            isJumpToLogin = true;
        }
    }

    @Override
    public void onError(NetErrorException throwable) {
        toast(throwable.getMessage());
    }

    @Override
    public void toast(String msg) {
        if (!TextUtils.isEmpty(msg))
            Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
    }

    NestedScrollView scrollerview;

    protected void registScrollToTop(NestedScrollView view) {
        this.scrollerview = view;
    }

    protected void registScrollToTop(int resId) {
        scrollerview = findViewById(resId);
    }

    public void goTop(View view) {
        if (scrollerview != null) {
            scrollerview.fullScroll(View.FOCUS_UP);//滚到底部
        }
    }

    public void goBottom(View view) {
        if (scrollerview != null) {
            scrollerview.fullScroll(View.FOCUS_DOWN);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {

            case LoginActivity.REQUEST_CODE:
                isJumpToLogin = false;
                if (resultCode == RESULT_OK)
                    initData();
//                else
//                    finish();
                break;
        }
    }

    @Override
    public void clearNetWork() {
        if (mCompositeDisposable != null) {
            mCompositeDisposable.clear(); // clear时网络请求会随即cancel
            mCompositeDisposable = null;
        }
    }
}
